package Unsubscribe;
use Campaign;

sub new
{
	my ($class)		= @_;		
	my $self		= {};

	$self->{unsubscribe_id}	= '';
	$self->{recipient_key}	= '';
	$self->{recipient_key}	= '';
	$self->{client_ip}	= '';

	bless $self, 'Unsubscribe';
	return $self;
}

sub newFromDB
{
	my ($class, $unsubscribe_id)	= @_;
	my $self		= {};

	my $stmt	= "SELECT id, recipient_key, ip, server_time, campaign_id
			   FROM unsubscribes WHERE id = $unsubscribe_id";

	my $hashref	= $Utils::kit_db->GetSingleRow($stmt);

	$self->{unsubscribe_id}	= $unsubscribe_id;
	$self->{recipient_key}	= $hashref->{recipient_key};
	$self->{client_ip}	= $hashref->{ip};
	$self->{server_time}	= $hashref->{server_time};
	$self->{campaign_id}	= $hashref->{campaign_id};

	bless $self, 'Unsubscribe';
	return $self;
}

sub InsertUnsubscribe
{
	my ($self)	= @_;
	my $stmt	= "INSERT INTO unsubscribes (recipient_key, ip, campaign_id)
			   VALUES (\"$self->{recipient_key}\", \"$self->{client_ip}\", $self->{campaign_id})";
# print $stmt; exit;
	return $Utils::kit_db->Insert($stmt);
}

sub GetCampaignUnsubscribes
{
	my ($self, $campaign_id)	= @_;
	my $stmt	= "SELECT id, recipient_key, ip, server_time
			   FROM   unsubscribes 
			   WHERE  campaign_id = $campaign_id";

	my @rows	= $Utils::kit_db->GetMultipleRows($stmt);
	my @unsubscribes	= ();
# print $stmt; exit;
	foreach (@rows) 
	{
		my $unsubscribe_id	= $_->[0];
		my $ip		= $_->[2];
		my $server_time	= $_->[3];

		my $recipient		= newFromDBByKey Recipient($_->[1]);
		my $rcpt_name		= $recipient->{f_name} . ' ' . $recipient->{l_name};
		my $company_name_short	= $recipient->{company_name_short};

		my $campaign	= newFromDB Campaign($campaign_id);

		my %unsubscribe	= (
			unsubscribe_id	=> $unsubscribe_id,
			recipient_name	=> $rcpt_name,
			ip		=> $ip,
			server_time	=> $server_time,
			company_name_short => $company_name_short,
			email		=> $recipient->{email_addr},
		);
# 		print "id = " . $unsubscribe_id . "<br>";
		push @unsubscribes, \%unsubscribe;
	}
	return @unsubscribes;
}

1;